const express = require('express')
const http = require('http')
const mstsc = require('./server/mstsc')
const fs = require('fs')

let list = JSON.parse(fs.readFileSync('./server/rdp.json')) || []

const app = express();
app.use('/', express.static(__dirname + '/client'))
app.get('/rdp/list', (req, res)=>{
	res.json(list.map(s=>({ ...s, password: null })))
})
app.post('/rdp/delete/:id', (req, res)=>{
	list = list.filter(s=>s.id !== req.params.id)
	res.json(list)
})
const server = http.createServer(app).listen(process.env.PORT || 9250)
const remote = mstsc(server, {
	getServer: (id) => {
		return list.find(s=>s.id === id)
	},
	connecting: (client, info) => {
		console.log('[mstsc] connecting ' + info.ip + ':' + info.port);
		const h = list.find(s=>s.ip === info.ip) || { ip: info.ip }
		if(!h.id){
			h.id = Math.random().toString(36).substring(2)
		}
		h.username = info.username
		h.password = info.password
		list = list.filter(s=>s.ip !== info.ip).concat(h)
		fs.writeFileSync('./server/rdp.json', JSON.stringify(list))
	}
})

//系统退出时清理资源
const shutdownHandler = () => {
	console.log('收到关闭信号，开始执行清理操作...')
	remote.close()
	server.close()
	process.exit(0)
}

process.on('SIGTERM', shutdownHandler)
process.on('SIGINT', shutdownHandler)

console.log(`server start at http://localhost:${process.env.PORT || 9250}`)